/* eslint-disable @typescript-eslint/no-misused-promises */
// src/middleware/upload.middleware.ts
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import * as multer from 'multer';
import { MinioService } from '../upload-minio/minio.service';

@Injectable()
export class MinioMiddleware implements NestMiddleware {
  private upload: multer.Multer;

  constructor(private readonly minioService: MinioService) {
    // 确保存储桶存在
    this.minioService.ensureBucketExists().catch(console.error);

    // 配置内存存储
    this.upload = multer({
      storage: multer.memoryStorage(),
      limits: {
        fileSize: 10 * 1024 * 1024, // 10MB限制
      },
    });
  }

  use(req: Request, res: Response, next: NextFunction) {
    // 使用 multer 处理文件上传
    void this.upload.single('file')(req, res, async (err) => {
      if (err) {
        return res.status(400).json({
          message: '文件上传失败',
          error: err.message,
        });
      }
      if (!req.file) {
        return next();
      }
      try {
        // 上传到 MinIO
        const fileName = await this.minioService.uploadFile(req.file);
        const fileUrl = await this.minioService.getFileUrl(fileName);

        // 将文件信息附加到请求对象
        req['uploadedFile'] = {
          originalName: req.file.originalname,
          fileName,
          size: req.file.size,
          mimeType: req.file.mimetype,
          url: fileUrl,
        };
        next();
      } catch (uploadError) {
        return res.status(500).json({
          message: '文件存储失败',
          error: uploadError.message,
        });
      }
    });
  }
}
